﻿#include "ExpEditDlg.h"
#include "ui_ExpEditDlg.h"
#include "mymainwindow.h"
#include "selectio.h"
#include <QString>
#include <QListWidgetItem>
#include <QMessageBox>
#include <QSize>
//二次计算表达式对话框ccg
ExpEditDlg::ExpEditDlg(unsigned int CurRecordId, QWidget *parent) :
    QDialog(parent),
    ui(new Ui::ExpEditDlg)
{
	m_TranslateResult = -1;
	memset((char*)&m_ExpDefine, 0, sizeof(rExpDefine_Info));
	m_pColumnInfo = NULL;
	m_pDataOffset = NULL;
	m_columnNum = 0;
	m_RecordLength = 0;
	ReleasColumnInfo();
	g_DbCfgFunObj.GetCurTableColumnInfo(SYSTEM_TYPE_NSA_YD, TABLE_REXPVARIABLE_LIST, (char*&)m_pColumnInfo, m_pDataOffset, m_columnNum, m_RecordLength);

    ui->setupUi(this);
	setModal(true);
	ui->rb_exp->setChecked(true);
	m_CurRecordId = CurRecordId;
	ui->pInputLstWdgt->setAlternatingRowColors(true);
	connect(ui->pDelInputBtn, SIGNAL(clicked()), this, SLOT(DelOneBtn()));
	connect(ui->pDelAllInputBtn, SIGNAL(clicked()), this, SLOT(DelAllBtn()));
	connect(ui->pCompileBtn, SIGNAL(clicked()), this, SLOT(CompileExp()));
	connect(ui->pAffirmBtn, SIGNAL(clicked()), this, SLOT(AffirmBtn()));
	connect(ui->pinsertBtn, SIGNAL(clicked()), this, SLOT(InsertBtn()));
	connect(ui->pCancelBtn, SIGNAL(clicked()), this, SLOT(close()));
	connect(ui->pbtn_expout, SIGNAL(clicked()), this, SLOT(expout_link()));
	connect(ui->pAll_OR_Btn, SIGNAL(clicked()), this, SLOT(AutoAllOrExp()));
	connect(ui->pAll_And_Btn, SIGNAL(clicked()), this, SLOT(AutoAllANDexp()));
	connect(ui->IotreeWidget, SIGNAL(itemClicked(QTreeWidgetItem *, int)), this, SLOT(uitem_click(QTreeWidgetItem *, int)));	
	connect(ui->IotreeWidget, SIGNAL(itemDoubleClicked(QTreeWidgetItem *, int)), this, SLOT(item_doubleclick(QTreeWidgetItem *, int)));
	InitDlgShow();
}

ExpEditDlg::~ExpEditDlg()
{
	ReleasColumnInfo();
    delete ui;
}


void ExpEditDlg::changeEvent(QEvent *e)
{
    QDialog::changeEvent(e);
    switch (e->type()) {
    case QEvent::LanguageChange:
        ui->retranslateUi(this);
        break;
    default:
        break;
    }
}

//说明
void ExpEditDlg::Explain_Btn()
{
	
}

void ExpEditDlg::Explain_Text()
{

}
void ExpEditDlg::InitRecdlg()
{
	char *pBuff = NULL;
	int	Buff_len = 0;
	int	Ret = 0;
	IOTreeTypeS data;
	QVariant ItemVariData;
	if(m_CurRecordId <= 0)
	{
		ui->le_expname->setText(QString::fromLocal8Bit("表达式"));
		memset(&m_pre_exp,0,sizeof(rExpDefine_Info));
	}
	else
	{
		Ret = g_DbCfgFunObj.GetRecordBuffbyAppType_TableId_RecordId(SYSTEM_TYPE_NSA_YD, TABLE_REXPDEFINE_INFO,m_CurRecordId, pBuff, &Buff_len);
		if (Ret>0 && pBuff && Buff_len>0)
		{
			memcpy(&m_pre_exp,pBuff,sizeof(rExpDefine_Info));
			ui->le_expname->setText(QString::fromLocal8Bit(m_pre_exp.Name));
            ui->le_expstr->setText(QString::fromLocal8Bit(m_pre_exp.express));

			if(m_pre_exp.expExpType == ENUM_EXP_TYPE_EXP)ui->rb_exp->setChecked(true);
			if(m_pre_exp.expExpType == ENUM_EXP_TYPE_DOUBLEDOT)ui->rb_double->setChecked(true);
			if(m_pre_exp.expExpType == ENUM_EXP_TYPE_SGZ)ui->rb_sgz->setChecked(true);

			QString recname,outioname;
			unsigned int devparentid;
			g_DbCfgFunObj.GetParentIdForSIYAO(m_pre_exp.out_tableid,m_pre_exp.out_ID%PARENT_OFFSET,devparentid);

			g_DbCfgFunObj.GetRecordNamebyAppType_TableId_RecordId(SYSTEM_TYPE_NSA_YD,TABLE_RDEVS_INFO,devparentid%PARENT_OFFSET,recname);
			outioname = recname;
			g_DbCfgFunObj.GetRecordNamebyAppType_TableId_RecordId(SYSTEM_TYPE_NSA_YD,m_pre_exp.out_tableid,m_pre_exp.out_ID%PARENT_OFFSET,recname);
			outioname = outioname +"  :  "+recname;
			ui->pbtn_expout->setText(outioname);
			if (pBuff)
			{
				delete [](unsigned char*)pBuff;
				pBuff = NULL;
			}
			if(m_pre_exp.expVarNum >0)
			{
                Ret =  g_DbCfgFunObj.GetRecordBuffbyAppType_TableId_ParentId(SYSTEM_TYPE_NSA_YD, TABLE_REXPVARIABLE_LIST,m_pre_exp.ID+PARENT_OFFSET*TABLE_REXPDEFINE_INFO, pBuff, &Buff_len, true);
				if (Ret>0 && pBuff && Buff_len>0)
				{
					for (int i=0; i<Ret; i++)
					{
						data.tableid = ((rExpVariable_List *)pBuff)[i].io_tableid;
						data.devaddr = ((rExpVariable_List *)pBuff)[i].io_devtype;
						data.devtype = ((rExpVariable_List *)pBuff)[i].io_addr;
                        data.indexno = ((rExpVariable_List *)pBuff)[i].io_indexno;
                        data.id = ((rExpVariable_List *)pBuff)[i].io_ID;
             
						QListWidgetItem *pitem = new QListWidgetItem;
						ItemVariData.setValue<IOTreeTypeS>(data);
						pitem->setData(Qt::UserRole, ItemVariData);

						QString recname,outioname;
						unsigned int devparentid;
						g_DbCfgFunObj.GetParentIdForSIYAO(data.tableid,data.id%PARENT_OFFSET,devparentid);

						g_DbCfgFunObj.GetRecordNamebyAppType_TableId_RecordId(SYSTEM_TYPE_NSA_YD,TABLE_RDEVS_INFO,devparentid%PARENT_OFFSET,recname);
						outioname = recname;
						g_DbCfgFunObj.GetRecordNamebyAppType_TableId_RecordId(SYSTEM_TYPE_NSA_YD,data.tableid,data.id%PARENT_OFFSET,recname);
						outioname = QString("b%1  ").arg(i+1)+outioname +"  :  "+recname;

						pitem->setText(outioname);
						ui->pInputLstWdgt->insertItem(ui->pInputLstWdgt->count(),pitem);

					}
				}
			}
		}
		
	}
}
void ExpEditDlg::InitDlgShow()
{
	InitIoTree();
	InitRecdlg();
	return ;
}
void ExpEditDlg::InitIoTree()
{
	char *pBuff = NULL;
	int	Buff_len = 0;
	int	Ret = 0;
	QString ItemText;
	IOTreeTypeS data;
	QVariant ItemVariData;
	QTreeWidgetItem *pDevItem;
	data.tableid = TABLE_RTASK_INFO;
	data.id = 0;
	data.parentid = 0;
	Item_Root = new QTreeWidgetItem((QTreeWidget*)0,QStringList(QString::fromLocal8Bit("设备")));
	Item_Root->setFlags(Qt::ItemIsSelectable| Qt::ItemIsEnabled);
	ItemVariData.setValue<IOTreeTypeS>(data);
	Item_Root->setData(0, Qt::UserRole,ItemVariData);
	Ret = g_DbCfgFunObj.GetRecordBuffbyAppType_TableId(SYSTEM_TYPE_NSA_YD, TABLE_RDEVS_INFO, pBuff, &Buff_len, true);
	if (Ret>0 && pBuff && Buff_len>0)
	{
		for (int i=0; i<Ret; i++)
		{
			data.id = ((rDevS_Info *)pBuff)[i].ID;
			data.tableid = TABLE_RDEVS_INFO;
			data.parentid = ((rDevS_Info *)pBuff)[i].ParentId;
			data.devaddr = ((rDevS_Info *)pBuff)[i].m_devaddr;
			data.devtype = ((rDevS_Info *)pBuff)[i].m_devtype;
			pDevItem = new QTreeWidgetItem(Item_Root);
			pDevItem->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled);
			pDevItem->setText(0,QString::fromLocal8Bit(((rDevS_Info *)pBuff)[i].Name));
			ItemVariData.setValue<IOTreeTypeS>(data);
			pDevItem->setData(0, Qt::UserRole,ItemVariData);

		}
	}
	if (pBuff)
	{
		delete [](unsigned char*)pBuff;
		pBuff = NULL;
	}
	items.append(Item_Root);
	ui->IotreeWidget->insertTopLevelItems(0,items);
	ui->IotreeWidget->expandItem(Item_Root);
}
void ExpEditDlg::InitVarListShow()
{
	
}

void ExpEditDlg::vdSetFormulaStruct()
{
	if (m_ExpDefine.ID<=0)
	{
		return;
	}

}

//获取二次计算输入量
void ExpEditDlg::GetExpVarList()
{
	
}
void ExpEditDlg::DeleteVarFromDB(int parentid)
{
	if (parentid<=0)
	{
		return;
	}
	char sql[SQL_MAX_LEN];
	memset(sql, 0, SQL_MAX_LEN);
	sprintf(sql, "delete from rexpvariable_list where ParentId=%d", parentid+PARENT_OFFSET*TABLE_REXPDEFINE_INFO);
	g_pSqLiteDB.DB_Modify(sql);
}

void ExpEditDlg::CompileExp()
{	
	memset(m_pre_exp.express,0,sizeof(m_pre_exp.express));
	if(!ui->le_expstr->text().isEmpty())
    sprintf(m_pre_exp.express,"%s",ui->le_expstr->text().toLocal8Bit().data());
	if(check_exp_validty(&m_pre_exp))
	{
      QMessageBox::information(NULL, QString::fromLocal8Bit("提示"), QString::fromLocal8Bit("编译成功"));
	}
	
}
void ExpEditDlg::AutoAllOrExp()
{
	char buf[1024];
	char buf_t[10];
	int rows;
	rows = ui->pInputLstWdgt->count();
	if(rows <0)
	{
		return;
	}
	memset(buf,0,sizeof(buf));
	for(int i =0;i<rows;i++)
	{
     sprintf(buf_t,"b%d",i+1);
	 strcat(buf,buf_t);
	 if(i!= rows-1)strcat(buf,"||");
	 else strcat(buf,";");
	}
	ui->le_expstr->setText(QString::fromLocal8Bit(buf));
}
void ExpEditDlg::AutoAllANDexp()
{
	char buf[1024];
	char buf_t[10];
	int rows;
	rows = ui->pInputLstWdgt->count();
	if(rows <0)
	{
		return;
	}
	memset(buf,0,sizeof(buf));
	for(int i =0;i<rows;i++)
	{
		sprintf(buf_t,"b%d",i+1);
		strcat(buf,buf_t);
		if(i!= rows-1)strcat(buf,"&&");
		else strcat(buf,";");
	}
	ui->le_expstr->setText(QString::fromLocal8Bit(buf));
}
void ExpEditDlg::AddBtn()
{
	
}

void ExpEditDlg::ReleasColumnInfo()
{
	
}

int ExpEditDlg::SaveData()
{
	return 1;
}

void ExpEditDlg::DelOneBtn()
{
	int rows;
   	rows = ui->pInputLstWdgt->currentRow();
	if(rows <0)
	{
		QMessageBox::information(NULL, QString::fromLocal8Bit("Warn"), QString::fromLocal8Bit("请选择删除项"));
        return;
	}
	ui->pInputLstWdgt->takeItem(rows);
	refreshInputlist();
}
void ExpEditDlg::expout_link()
{
    SelectIo dlg;
	QString ioname;
	dlg.exec();
    if(!dlg.getok())return;
	dlg.getio(&expout_data,ioname);
	m_pre_exp.out_tableid = expout_data.tableid;
	m_pre_exp.out_devtype = expout_data.devtype;
	m_pre_exp.out_addr = expout_data.devaddr;
	m_pre_exp.out_indexno = expout_data.indexno;
	m_pre_exp.out_ID = expout_data.id%PARENT_OFFSET+PARENT_OFFSET*expout_data.tableid;
	ui->pbtn_expout->setText(ioname);

}
void ExpEditDlg::DelAllBtn()
{
	ui->pInputLstWdgt->clear();
}

void ExpEditDlg::AffirmBtn()
{
	int ret = InsertExpRecord(m_CurRecordId);
	if(ret <0)return;
	close();
}
void ExpEditDlg::refreshInputlist()
{
	QString itemtext;
	int pos;
   for(int i =0;i<ui->pInputLstWdgt->count();i++)
   {
      itemtext = ui->pInputLstWdgt->item(i)->text();
	  pos  = itemtext.indexOf(" ");
	  itemtext = itemtext.remove(0,pos);
      itemtext = QString("b%1").arg(i+1) + itemtext;
      ui->pInputLstWdgt->item(i)->setText(itemtext);
   }
}
void ExpEditDlg::InsertBtn()
{
	int rows;
	IOTreeTypeS tree_data;
    QTreeWidgetItem * ptreeitem;


	if(ui->pInputLstWdgt->count() >= EXP_IO_MAX_NUM)
	{
		QMessageBox::information(NULL, QString::fromLocal8Bit("警告"), QString::fromLocal8Bit("输入点数超过最大点数"));
		return;
	}

	ptreeitem = ui->IotreeWidget->currentItem();
    if(!ptreeitem)return;
    tree_data = ptreeitem->data(0, Qt::UserRole).value<IOTreeTypeS>();
	if(tree_data.tableid != TABLE_RDEVS_YC &&tree_data.tableid != TABLE_RDEVS_YX)return;
	if(tree_data.id <=0)return;

	if(isexist(tree_data))
	{
		QMessageBox::information(NULL, QString::fromLocal8Bit("警告"), QString::fromLocal8Bit("该点已经存在"));
		return;
	}

	QListWidgetItem *pitem = new QListWidgetItem;
	
	QString devname = ptreeitem->parent()->parent()->text(0);
	QString ioname = ptreeitem->text(0);

	QVariant ItemVariData;
	ItemVariData.setValue<IOTreeTypeS>(tree_data);
	pitem->setData(Qt::UserRole,ItemVariData);
	rows = ui->pInputLstWdgt->currentRow();
	if(rows <0)
	{
	    rows = 	ui->pInputLstWdgt->count();
	}
	pitem->setText(QString("b%1  ").arg(rows+1)+devname +"  :  " +ioname);
	ui->pInputLstWdgt->insertItem(rows+1,pitem);
	refreshInputlist();
}
void ExpEditDlg::CompileBtn()
{
	
}
void ExpEditDlg::ExpType_slot()
{
	
}
bool ExpEditDlg::isexist(IOTreeTypeS data)
{
    IOTreeTypeS itemdata;
	for(int i =0;i<ui->pInputLstWdgt->count();i++)
	{
        itemdata = ui->pInputLstWdgt->item(i)->data(Qt::UserRole).value<IOTreeTypeS>();
		if(itemdata.tableid == data.tableid && itemdata.id == data.id)return true;
	}
	return false;
}
void ExpEditDlg::uitem_click(QTreeWidgetItem * item, int column)
{
	IOTreeTypeS data_parent,data;
    data_parent = item->data(0, Qt::UserRole).value<IOTreeTypeS>();
    if(data_parent.tableid != TABLE_RDEVS_INFO)
	{
		if(item->childCount()>0)
		{
          item->setExpanded(true);
		}
		return;
	}
	if(item->childCount()>0)return;
	char *pBuff = NULL;
	int	Buff_len = 0;
	int	Ret = 0;
	QString ItemText;
	QVariant ItemVariData;
	QTreeWidgetItem *pItem,*pItem_io;
	
	Ret = g_DbCfgFunObj.GetRecordBuffbyAppType_TableId_ParentId(SYSTEM_TYPE_NSA_YD, TABLE_RDEVS_YX,data_parent.id+PARENT_OFFSET*TABLE_RDEVS_INFO, pBuff, &Buff_len, true);
	if (Ret>0 && pBuff && Buff_len>0)
	{
		pItem = new QTreeWidgetItem(item);
		pItem->setFlags(Qt::ItemIsSelectable| Qt::ItemIsEnabled);
		memset(&data,0,sizeof(IOTreeTypeS));
		data.tableid = TABLE_RDEVS_YX;
		ItemVariData.setValue<IOTreeTypeS>(data);
		pItem->setData(0, Qt::UserRole,ItemVariData);
		pItem->setText(0,QString::fromLocal8Bit("遥信"));
		for (int i=0; i<Ret; i++)
		{
			data.id = ((rDevS_Yx *)pBuff)[i].ID;
			data.tableid = TABLE_RDEVS_YX;
			data.parentid = ((rDevS_Yx *)pBuff)[i].ParentId;
			data.devtype = data_parent.devtype;
            data.devaddr = data_parent.devaddr;
            data.indexno = ((rDevS_Yx *)pBuff)[i].IndexNo;
			pItem_io = new QTreeWidgetItem(pItem);
			pItem_io->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled);
			pItem_io->setText(0,QString::fromLocal8Bit(((rDevS_Yx *)pBuff)[i].Name));
			ItemVariData.setValue<IOTreeTypeS>(data);
			pItem_io->setData(0, Qt::UserRole,ItemVariData);

		}
	}
	if (pBuff)
	{
		delete [](unsigned char*)pBuff;
		pBuff = NULL;
	}

	Ret = g_DbCfgFunObj.GetRecordBuffbyAppType_TableId_ParentId(SYSTEM_TYPE_NSA_YD, TABLE_RDEVS_YC,data_parent.id+PARENT_OFFSET*TABLE_RDEVS_INFO, pBuff, &Buff_len, true);
	if (Ret>0 && pBuff && Buff_len>0)
	{
		pItem = new QTreeWidgetItem(item);
		pItem->setFlags(Qt::ItemIsSelectable| Qt::ItemIsEnabled);
		memset(&data,0,sizeof(IOTreeTypeS));
		data.tableid = TABLE_RDEVS_YC;
		ItemVariData.setValue<IOTreeTypeS>(data);
		pItem->setData(0, Qt::UserRole,ItemVariData);
		pItem->setText(0,QString::fromLocal8Bit("遥测"));
		for (int i=0; i<Ret; i++)
		{
			data.id = ((rDevS_Yc *)pBuff)[i].ID;
			data.tableid = TABLE_RDEVS_YC;
			data.parentid = ((rDevS_Yc *)pBuff)[i].ParentId;
			data.devtype = data_parent.devtype;
			data.devaddr = data_parent.devaddr;
			data.indexno = ((rDevS_Yc *)pBuff)[i].IndexNo;
			pItem_io = new QTreeWidgetItem(pItem);
			pItem_io->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled);
			pItem_io->setText(0,QString::fromLocal8Bit(((rDevS_Yc *)pBuff)[i].Name));
			ItemVariData.setValue<IOTreeTypeS>(data);
			pItem_io->setData(0, Qt::UserRole,ItemVariData);

		}
	}
	if (pBuff)
	{
		delete [](unsigned char*)pBuff;
		pBuff = NULL;
	}

	ui->IotreeWidget->expandItem(item);

}
void ExpEditDlg::item_doubleclick(QTreeWidgetItem * item, int column)
{
	IOTreeTypeS data_parent,data;
	QVariant ItemVariData;
	if(ui->pInputLstWdgt->count() >= EXP_IO_MAX_NUM)
	{
		QMessageBox::information(NULL, QString::fromLocal8Bit("警告"), QString::fromLocal8Bit("输入点数超过最大点数"));
		return;
	}
	data_parent = item->data(0, Qt::UserRole).value<IOTreeTypeS>();
	if(data_parent.tableid != TABLE_RDEVS_YC &&data_parent.tableid != TABLE_RDEVS_YX)return;
	if(data_parent.id <=0)return;
	if(isexist(data_parent))
	{
		QMessageBox::information(NULL, QString::fromLocal8Bit("警告"), QString::fromLocal8Bit("该点已经存在"));
		return;
	}
    QString devname = item->parent()->parent()->text(0);
	QString ioname = item->text(0);
	QListWidgetItem *pitem = new QListWidgetItem;
	ItemVariData.setValue<IOTreeTypeS>(data_parent);
	pitem->setData(Qt::UserRole, ItemVariData);
	pitem->setText(QString("b%1  ").arg(ui->pInputLstWdgt->count()+1)+devname +"  :  " +ioname);
	ui->pInputLstWdgt->insertItem(ui->pInputLstWdgt->count(),pitem);
}
int ExpEditDlg::InsertExpRecord(int m_expid)
{
	int	Ret = 0;
	unsigned int	RecordId = 0;
	//rExpDefine_Info rExp;
	m_ColInfo.InitColumnInfo(SYSTEM_TYPE_NSA_YD, TABLE_REXPDEFINE_INFO);
	if (!m_ColInfo.IsSafe())
	{
		m_ColInfo.ReleasColumnInfo();
		return -1;
	}	
	if(m_expid <=0)
	{
		if (g_DbCfgFunObj.GetNewFreeId(SYSTEM_TYPE_NSA_YD, TABLE_REXPDEFINE_INFO, RecordId)>0)
		{
			m_pre_exp.ID = RecordId;
		}else
		{
			QMessageBox::information(this, QString::fromLocal8Bit("数据库组态"), QString::fromLocal8Bit("获取空闲设备ID失败！"), QMessageBox::Ok | QMessageBox::Cancel);
			m_ColInfo.ReleasColumnInfo();
			return -2;
		}
	}
	else
	{ 
       m_pre_exp.ID = m_expid;
	}
	m_exp_varnum = ui->pInputLstWdgt->count();
	m_pre_exp.expVarNum = m_exp_varnum;
	char tableName[TABLE_ENG_NAME_LEN];
	memset(tableName, 0, TABLE_ENG_NAME_LEN);
	sprintf(tableName, "rExpDefine_Info");
	sprintf(m_pre_exp.Name,"%s",ui->le_expname->text().toLocal8Bit().data());
	sprintf(m_pre_exp.express,"%s",ui->le_expstr->text().toLocal8Bit().data());
	if(ui->rb_exp->isChecked())m_pre_exp.expExpType = ENUM_EXP_TYPE_EXP;
	if(ui->rb_double->isChecked())m_pre_exp.expExpType = ENUM_EXP_TYPE_DOUBLEDOT;
	if(ui->rb_sgz->isChecked())m_pre_exp.expExpType = ENUM_EXP_TYPE_SGZ;


	if(!check_exp_validty(&m_pre_exp))return -3;

	Ret = g_DbCfgFunObj.InsertRecordIntoDB(SYSTEM_TYPE_NSA_YD, TABLE_REXPDEFINE_INFO, (char*)&m_pre_exp, m_ColInfo.m_RecordLength, m_ColInfo.m_pColumnInfo, m_ColInfo.m_pDataOffset, m_ColInfo.m_columnNum, tableName);//组织SQL语句并插入
	if (Ret<0)
	{
		QMessageBox::information(this, QString::fromLocal8Bit("数据库组态"), QString::fromLocal8Bit("插入表达式记录失败！"), QMessageBox::Ok | QMessageBox::Cancel);
		m_ColInfo.ReleasColumnInfo();
		return -5;
	}

	m_ColInfo.ReleasColumnInfo();//删除之前获得的数据库表 列信息
	
	InsertExpVariableLst(m_pre_exp.ID);
	
	return 1;
}

int ExpEditDlg::InsertExpVariableLst(unsigned int ExpId)
{
	if (ExpId<=0 )
	{
		return -1;
	}

	int				Ret = 0;
	int				Result = 0;
	rExpVariable_List		rExpVarLst;
	int				i=0;
	unsigned int	RecStartId = 0;
	IOTreeTypeS     itemdata;
	QString			SqlStr;
	QString			InsertHeadSqlStr;
	QString			InsertValSqlStr;
	char			tableName[TABLE_ENG_NAME_LEN];
	bool			bFirstRowFlag = true;
	char			m_Dsql[SQL_MAX_LEN*2];
	memset(tableName, 0, TABLE_ENG_NAME_LEN);
	sprintf(tableName, "rExpVariable_List");

	m_ColInfo.InitColumnInfo(SYSTEM_TYPE_NSA_YD, TABLE_REXPVARIABLE_LIST);
	if (!m_ColInfo.IsSafe())
	{
		m_ColInfo.ReleasColumnInfo();
		return -2;
	}
	DeleteVarFromDB(ExpId);
	memset(m_Dsql, 0, SQL_MAX_LEN*2);

	m_exp_varnum = ui->pInputLstWdgt->count();

	if (m_exp_varnum>0 )
	{
			g_DbCfgFunObj.GetInsertHeadSql(SYSTEM_TYPE_NSA_YD, TABLE_REXPVARIABLE_LIST, tableName, InsertHeadSqlStr);

			g_DbCfgFunObj.GetNewFreeId(SYSTEM_TYPE_NSA_YD, TABLE_REXPVARIABLE_LIST, RecStartId);		
			bFirstRowFlag = true;
			for (i=0; i<m_exp_varnum; i++)
			{
				memset((char*)&rExpVarLst, 0, sizeof(rExpVariable_List));
				memset(&itemdata,0,sizeof(IOTreeTypeS));
                itemdata = ui->pInputLstWdgt->item(i)->data(Qt::UserRole).value<IOTreeTypeS>();
				rExpVarLst.ID =  RecStartId+i;              
				rExpVarLst.IndexNo = i+1;
                rExpVarLst.ParentId = ExpId+PARENT_OFFSET*TABLE_REXPDEFINE_INFO;
                rExpVarLst.io_tableid = itemdata.tableid;
                rExpVarLst.io_devtype = itemdata.devtype;
                rExpVarLst.io_addr = itemdata.devaddr;
                rExpVarLst.io_indexno = itemdata.indexno;
                rExpVarLst.io_ID = itemdata.id;
				
				g_DbCfgFunObj.GetValuesSql((char*)&rExpVarLst, m_ColInfo.m_RecordLength, m_ColInfo.m_pColumnInfo,  m_ColInfo.m_pDataOffset,  m_ColInfo.m_columnNum, OPER_ROW_INSERT, InsertValSqlStr);
				if (InsertValSqlStr.length()<=0)
				{
					continue;
				}
				if (bFirstRowFlag)
				{
					SqlStr = InsertHeadSqlStr;
					bFirstRowFlag = false;
				}else
				{
					SqlStr += QString::fromLocal8Bit(",");
				}

				SqlStr += InsertValSqlStr;
				if (SqlStr.toLocal8Bit().length() >= (SQL_MAX_LEN*2-200) )
				{
					sprintf(m_Dsql, "%s", SqlStr.toLocal8Bit().data());
					Result = g_pSqLiteDB.DB_Modify(m_Dsql);
					if (Result<0)
					{
						QMessageBox::information(this, QString::fromLocal8Bit("数据库组态"), QString::fromLocal8Bit("插入表达式输入点记录失败！"), QMessageBox::Ok | QMessageBox::Cancel);
						m_ColInfo.ReleasColumnInfo();
						return -5;
						break;
					}
					SqlStr.clear();
					bFirstRowFlag = true;
				}
			}
		}

		
		if (SqlStr.length()>0)
		{
			sprintf(m_Dsql, "%s", SqlStr.toLocal8Bit().data());
			Result = g_pSqLiteDB.DB_Modify(m_Dsql);
			if (Result<0)
			{
				QMessageBox::information(this, QString::fromLocal8Bit("数据库组态"), QString::fromLocal8Bit("插入表达式输入点记录失败！"), QMessageBox::Ok | QMessageBox::Cancel);
				m_ColInfo.ReleasColumnInfo();
				return -5;
			}
			SqlStr.clear();
		}
		m_ColInfo.ReleasColumnInfo();
		return m_exp_varnum;
}



int  ExpEditDlg::rExpChk(char *pStr,char *pExp)
{ 
	OPR_PRI OprPri[]=
	{
		{"$",     0},  
		{"||",    2},
		{"&&",    4},
		{"==",   12},
		{"!=",   12},
		{"<=",   14},
		{">=",   14},
		{"<<",   16},
		{">>",   16}, 
		{"=",     1},
		{"|",     6},
		{"^",     8},
		{"&",    10},
		{"<",    14},
		{">",    14},
		{"+",    18},
		{"-",    18},
		{"*",    20},
		{"/",    20},
		{"%",    20},
		{"max",  20},
		{"min",  20},
		{"pow",  22},
		{"sqrt", 24},
		{"abs",  24},
		{"log",  24},
		{"exp",  24},
		{"ln",   24},
		{"sin",  24},
		{"cos",  24},
		{"tan",  24},
		{"asin", 24},
		{"acos", 24},
		{"atan", 24},
		{"~",    24},
		{"!",    24},
		{""  ,   80},
	};
	char Var[EXP_IO_MAX_NUM][4]=
	{"b50","b49","b48","b47","b46","b45","b44","b43","b42","b41",
	"b40","b39","b38","b37","b36","b35","b34","b33","b32","b31",
	"b30","b29","b28","b27","b26","b25","b24","b23","b22","b21",
	"b20","b19","b18","b17","b16","b15","b14","b13","b12","b11",
	"b10","b9","b8","b7","b6","b5","b4","b3","b2","b1"};  

	unsigned char *pOpr,PreFlag,Flag;                   
	unsigned short OprCnt,ExpCnt,StrCnt; 
	unsigned short i,j;
	for(i=0;i<255;i++)pExp[i]=NULL;

	if (strlen(pStr)==0)  return (-1);                  /* no string */
	if (pStr[strlen(pStr)-1]!=';')  return (-2);        /* string not end in ';' */

	pOpr=(unsigned char *)malloc(256);

	PreFlag=0;
	OprCnt=0;
	ExpCnt=0;
	StrCnt=0;
	pOpr[OprCnt++]=0;

	for (i=0;i<400;i++)
	{  
		if (pStr[StrCnt]==' ')  StrCnt++;
		else if (((pStr[StrCnt]>='0') && (pStr[StrCnt]<='9')) || (pStr[StrCnt]=='.'))
		{ 
			if (PreFlag!=0)  return (-3);                   /* constant following variable */
			pExp[ExpCnt++]='C';
			while (((pStr[StrCnt]>='0') && (pStr[StrCnt]<='9')) || (pStr[StrCnt]=='.'))
			{
				pExp[ExpCnt]=pStr[StrCnt];
				ExpCnt++;
				StrCnt++;
			}
			PreFlag=1;
		} 
		else if ((pStr[StrCnt]=='b') || (pStr[StrCnt]=='B'))
		{ 
			if (PreFlag!=0)  return (-4);                   /* variable following variable or constant */
			Flag=0;
			for (j=0;j<EXP_IO_MAX_NUM;j++)
			{
				if (strnicmp(&pStr[StrCnt],Var[j],strlen(Var[j]))==0)
				{
					pExp[ExpCnt]='B';
					/*pExp[ExpCnt+1]='C'+20-(char)j;*/
					pExp[ExpCnt+1]='C'+EXP_IO_MAX_NUM-(char)j;
					ExpCnt=ExpCnt+2;
					StrCnt=StrCnt+strlen(Var[j]); 
					Flag=1;
					PreFlag=2;
					break;
				}
			}
			if (Flag==0)  return (-5);                      /* variable name error */
		}
		else if (pStr[StrCnt]=='(')
		{
			pOpr[OprCnt]=0;
			OprCnt++; 
			StrCnt++;
		}
		else if ((pStr[StrCnt]==')') || (pStr[StrCnt]==';'))
		{
			if (pOpr[OprCnt-1]!=0)
			{
				pExp[ExpCnt]='A';
				pExp[ExpCnt+1]='C'+pOpr[OprCnt-1];
				ExpCnt=ExpCnt+2;
				OprCnt--;
			}
			else
			{  
				OprCnt--;
				if (pStr[StrCnt]==';')
				{
					if (OprCnt!=0)  return (-6);
					else return (0);
				}
				else
					if (OprCnt<1)  return (-6);                 /* () dismatch */  
				StrCnt++;
			}
		}              
		else
		{ 
			Flag=0;              
			j=0;
			while (strcmp(OprPri[j].Opr,"")!=0)
			{ 
				if (strnicmp(&pStr[StrCnt],OprPri[j].Opr,strlen(OprPri[j].Opr))==0)
				{ 
					if ((PreFlag==0) && (OprPri[j].Pri<24))
						return (-7);                              /* operator following operator */
					if (OprPri[j].Pri>OprPri[pOpr[OprCnt-1]].Pri)
					{
						pOpr[OprCnt]=(unsigned char)j;
						OprCnt++;
						StrCnt=StrCnt+strlen(OprPri[j].Opr);
						PreFlag=0;
					}
					else
					{ 
						pExp[ExpCnt]='A';
						pExp[ExpCnt+1]='C'+pOpr[OprCnt-1];
						ExpCnt=ExpCnt+2;
						OprCnt--;
					} 
					Flag=1;
					break;
				}
				j++;
			}          
			if (Flag==0)  return (-8);                      /* operator error */
		} 
	}  
	return 0;
}

//检查表达式语法是否正确
bool ExpEditDlg::check_exp_validty(rExpDefine_Info  *pexp)
{
	QString str_exp;
	str_exp = QString::fromLocal8Bit(pexp->express);
	int len = str_exp.length();
	if(len<=0)
	{
		QMessageBox::information(NULL, QString::fromLocal8Bit("数据库组态"), QString::fromLocal8Bit("表达式不能为空"));
		return FALSE;
	}
	QString  s =str_exp.right(1);
	if(s.compare(";") !=0)
	{
		QMessageBox::information(NULL, QString::fromLocal8Bit("数据库组态"), QString::fromLocal8Bit("表达式缺少分号!"));
		return FALSE;
	}
	if(len>255)
	{
		QMessageBox::information(NULL, QString::fromLocal8Bit("数据库组态"), QString::fromLocal8Bit("表达式的长度超过256个字节,请检查!"));
		return FALSE;
	}
	memset(pexp->culexp,0,sizeof(pexp->culexp));
	if(rExpChk(pexp->express,pexp->culexp)!=0)
	{
		QMessageBox::information(NULL, QString::fromLocal8Bit("数据库组态"), QString::fromLocal8Bit("表达式有错误，请检查!"));
		return FALSE;
	}
	return TRUE;
}
